import { Button, Modal, Space, } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { Access, getDvaApp, history, useAccess } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import ProTable from '@ant-design/pro-table';
import { getNoticeList, noticeDelete } from '@/services/notice';
import $utils from '@/utils/utils';
import { platformNames } from '@/utils/common';
import moment from 'moment';

const initDate = {
    startTime: moment().subtract(30, 'days').startOf('day'),     //  开始时间
    endTime: moment().endOf('day'),     //  结束时间
};

const NoticeList: React.FC = () => {

    // 解决无法调用dispatch
    const dispatch = getDvaApp()._store.dispatch;
    // 获取权限
    const access = useAccess();
    const formRef = useRef<ProFormInstance>();
    const actionRef = useRef<ActionType>();
    const [initParams, setParams] = useState<any>();
    const [pageSize, setPageSize] = useState<number>(20);


    const l_state: any = history.location.state;
    useEffect(() => {
        if (!initParams) {
            const data = l_state ? {
                ...l_state,
                dateTime: [moment(l_state?.startTime) || initDate.startTime, moment(l_state?.endTime) || initDate.endTime],
            } : {
                ...initDate,
                dateTime: [initDate.startTime, initDate.endTime],
            };
            setParams(data);
        }
    }, []);

    // 筛选重置时更新表单
    useEffect(() => {
        const data = {
            ...initDate,
            dateTime: [initDate.startTime, initDate.endTime],
        }
        if (JSON.stringify(initParams) === JSON.stringify(data)) {
            formRef && formRef.current?.resetFields();
            actionRef?.current?.reset && actionRef?.current?.reset();
        }
    }, [initParams]);

    // 删除弹窗
    const confirm = (id: number) => {
        Modal.confirm({
            title: '删除',
            content: '确定是否要删除',
            centered: true,
            maskClosable: true,
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                // 删除通知
                const msg = await noticeDelete({ id });
                if (msg.code === 0) {
                    actionRef && (actionRef?.current?.reload());
                }
            }
        });
    };

    const columns: ProColumns<any>[] = [
        {
            title: '添加时间',
            dataIndex: 'dateTime',
            hideInTable: true,
            valueType: 'dateTimeRange',
            order: 9,
            colSize: 6 * 0.25,
            search: {
                transform: (value: any) => ({ startTime: value[0], endTime: value[1] }),
            },
            fieldProps: {
                disabledDate: (current: any) => {
                    // 只可选择90天内，上线日期后
                    return !(current > moment("06-14-2022", "MM-DD-YYYY").endOf('days') && current > moment().subtract(90, 'days') && current < moment().subtract(0, 'days').endOf('days'));
                },
                ranges: {
                    今天: [moment().startOf('day'), moment().endOf('day')],
                    昨天: [moment().subtract(1, 'days').startOf('day'), moment().subtract(1, 'days').endOf('day')],
                    本周: [moment().startOf('week'), moment().endOf('week')],
                    本月: [moment().startOf('month'), moment().endOf('month')],
                    上月: [
                        moment(moment().subtract({ day: new Date().getDate() - 1, month: 1 })),
                        moment(moment().subtract({ day: new Date().getDate(), month: 0 })),
                    ],
                }
            }
        },
        {
            title: '通知标题',
            dataIndex: 'title',
        },
        {
            title: '添加人',
            dataIndex: 'createName',
            hideInForm: true,
            search: {
                transform: (value: any) => ({ senderName: value }),
            },
        },
        {
            title: '添加时间',
            dataIndex: 'createTime',
            search: false,
            hideInForm: true,
            width: '120px',

        },
        {
            title: '接收终端',
            dataIndex: 'platforms',
            valueType: 'select',
            search: false,
            hideInForm: true,
            fieldProps: {
                options: platformNames,
            },
            render: (text: any, record: any) => {
                const data = record.platforms.split(',');
                let dom: any[] = [];
                data.map((item: any, index: number) => {
                    const platform = platformNames.find(i => i.value === +item);
                    platform && (dom.push(<div key={index}>{platform?.label}</div>))
                })
                return (<div> {dom.length > 0 ? dom.map((text: any) => {
                    return text
                }) : '--'}</div>)
            }
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => [
                <Space key={record.id}>
                    <Access accessible={access.can_numAll.delete}>
                        <Button type="primary" size="small" danger onClick={() => {
                            confirm(record.id)
                        }}>删除</Button>
                    </Access>

                </Space>
            ],
        },
    ];

    return (
        <PageContainer>
            {initParams && <ProTable<API.RuleListItem, API.PageParams>
                actionRef={actionRef}
                rowKey="id"
                pagination={{
                    pageSize: pageSize,
                    showSizeChanger: true,
                    size: 'small',
                    onShowSizeChange: (current, pageSize) => {
                        setPageSize(pageSize);
                    }
                }}
                form={{
                    initialValues: initParams
                }}
                formRef={formRef}
                search={access.can_numAll.search ? {
                    labelWidth: 120,
                    defaultCollapsed: false,
                    collapseRender: () => false,
                    span: {
                        xs: 24,
                        sm: 24,
                        md: 12,
                        lg: 12,
                        xl: 8,
                        xxl: 8,
                    },
                    optionRender: (searchConfig, formProps, dom) => [
                        dom.reverse()[0],
                        <Button
                            key="resetText"
                            onClick={() => {
                                const data = {
                                    ...initDate,
                                    dateTime: [initDate.startTime, initDate.endTime],
                                };
                                setParams(data);
                            }}
                        >
                            重置
                        </Button>,
                    ],
                } : false}
                options={false}
                title={() => [
                    <Access key="index" accessible={true}>
                        <Button type="primary" onClick={() => {
                            const newTab = {
                                name: `新建通知`,
                                path: '/OperationsMange/Notice/detail',
                                state: {
                                    status: 'create'
                                }
                            };
                            // 设置当前tab对象
                            $utils.setNewTab(dispatch, newTab);
                            $utils.addTab(dispatch, newTab)
                            history.push({
                                pathname: '/OperationsMange/Notice/detail',
                                state: {
                                    status: 'create'
                                }
                            });
                        }}>新建通知</Button>
                    </Access>

                ]}
                request={async (params: any) => {
                    if (!params.startTime) { params.startTime = initDate.startTime.format('YYYY-MM-DD HH:mm:ss'); }
                    if (!params.endTime) { params.endTime = initDate.endTime.format('YYYY-MM-DD HH:mm:ss'); }
                    const msg = await getNoticeList(params);
                    if (msg.code === 0) {
                        // 将筛选条件存进 tabs
                        $utils.addTab(dispatch, {
                            name: '通知中心',
                            path: '/OperationsMange/Notice',
                            isTopMenu: true,
                            state: params
                        });
                    }
                    return {
                        data: msg.body?.list || [],
                        success: msg.code === 0,
                        total: msg.body?.count,
                    }
                }}
                columns={columns}
            />}
        </PageContainer >
    );
};

export default NoticeList;
